package middleware

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type TokenAuthMiddleware struct {
}

func NewTokenAuthMiddleware() *TokenAuthMiddleware {
	return &TokenAuthMiddleware{}
}

func (m *TokenAuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("Auth")
		if token == "" {
			httpx.Error(w, errors.New("token为空"))
			return
		}

		token = "user:token:" + token
		store := redis.New("")
		userId, err := store.GetCtx(context.Background(), token)
		if err != nil {
			httpx.Error(w, errors.New("token错误"))
			return
		}

		// 将userId信息添加到上下文，方便后续使用
		ctx := context.WithValue(r.Context(), "userId", userId)
		next.ServeHTTP(w, r.WithContext(ctx))
	}
}
